package com.lk.server.rpc.handler;

import com.lk.entity.PingMessage;
import com.lk.entity.PongMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端的心跳handler
 */
@Slf4j
public class HeartBeatServerHandler extends SimpleChannelInboundHandler<PingMessage> {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //当服务器未从客户端使用超时收到任何检测信号时，服务器将关闭通道。
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case ALL_IDLE:
                    log.info("IdleStateEvent triggered, close channel ");
                    ctx.channel().close();
                    break;

            }
        }
        super.userEventTriggered(ctx, evt);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PingMessage msg) throws Exception {
        log.info("ping:{}", msg);
        if (msg.getPing().equals("ping")) {
            PongMessage pongMessage = new PongMessage();
            pongMessage.setPong("pong");
            ctx.writeAndFlush(pongMessage);
        }

    }
}
